package com.rock.code.system.dicGroup.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.rock.code.base.controller.BaseController;
import com.rock.code.base.domain.AjaxJson;
import com.rock.code.base.domain.Constants;
import com.rock.code.common.excel.ExportExcel;
import com.rock.code.common.exceptions.SystemException;
import com.rock.code.common.pager.Page;
import com.rock.code.common.tree.ItemNode;
import com.rock.code.system.dicGroup.domain.TbSysDicGroup;
import com.rock.code.system.dicGroup.service.TbSysDicGroupService;
import com.rock.code.system.user.domain.TbSysLoginmsg;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 字典分组管理
*
* @author wangwenbo
* @date 2018/01/17
*/
@Controller
@RequestMapping("/tbSysDicGroup")
public class TbSysDicGroupController extends BaseController {

    /**
    * The tbSysDicGroupServiceImpl
    */
    @Resource
    private TbSysDicGroupService tbSysDicGroupServiceImpl;

    /**
    * Dispatch.
    *
    * @return the string
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @RequestMapping("")
    public String dispatch() throws Exception {
        return "system/dicGroup/tbSysDicGroupList";
    }

    /**
    * queryPageList
    *
    * @return the page info
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/queryPageList", method = RequestMethod.POST)
    public PageInfo<TbSysDicGroup> queryPageList() throws Exception {
        Map<String, Object> param = this.getRequestMapSingle();
        Page page = new Page(request);
        PageInfo pageInfo = null;
        try {
            param.put("isDelete", Constants.DELETE_N);
            pageInfo = tbSysDicGroupServiceImpl.queryPageList(page, param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return pageInfo;
    }

    /**
    * querySingle
    *
    * @return TbSysDicGroup
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/querySingle", method = RequestMethod.POST)
    public TbSysDicGroup querySingle() throws Exception {
        Map<String, Object> param = this.getRequestMapSingle();
        TbSysDicGroup tbSysDicGroup = null;
        try {
            tbSysDicGroup = tbSysDicGroupServiceImpl.queryByParaMap(param);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return tbSysDicGroup;
    }

    /**
     * Query tree data.
     *
     * @param parentCode the input name
     * @return the json object
     * @throws Exception the exception
     * @author wangwenbo
     * @date 2018/01/17
     */
    @ResponseBody
    @RequestMapping(value = "/queryTreeData", method = RequestMethod.GET)
    public AjaxJson queryTreeData(String parentCode) throws Exception {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("parentCode", parentCode);
            param.put("isDelete", Constants.DELETE_N);
            param.put("orderBy", "VIEW_ORDER");
            List<ItemNode> rows = tbSysDicGroupServiceImpl.queryTreeData(param);
            ajaxJson.setResult(rows);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return ajaxJson;
    }

    /**
    * Save.
    *
    * @param tbSysDicGroup the TbSysDicGroup
    * @return the ajax json
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxJson save(@RequestBody TbSysDicGroup tbSysDicGroup) throws Exception {
        try {
            TbSysLoginmsg sessionUser = getSessionUser();
            if (isNotEmpty(tbSysDicGroup.getDicGroupId())) {
                tbSysDicGroup.setModifier(sessionUser.getLoginCode());
                tbSysDicGroup.setModifieDate(new Date());
                tbSysDicGroupServiceImpl.update(tbSysDicGroup);
            } else {
                // 根据父节点设置子节点的级别
                TbSysDicGroup parentNode = null;
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("dicGroupCode", tbSysDicGroup.getParentCode());
                map.put("isDelete", Constants.DELETE_N);
                parentNode = tbSysDicGroupServiceImpl.queryByParaMap(map);
                tbSysDicGroup.setTreeLevel(parentNode.getTreeLevel() + 1);
                // 设置子节点其他属性
                tbSysDicGroup.setIsDelete(Constants.DELETE_N);
                tbSysDicGroup.setCreater(sessionUser.getLoginCode());
                tbSysDicGroup.setCreateDate(new Date());
                tbSysDicGroup.setModifier(sessionUser.getLoginCode());
                tbSysDicGroup.setModifieDate(new Date());
                tbSysDicGroupServiceImpl.insert(tbSysDicGroup);
                // 更新父节点
                if (parentNode.getIsLeaf() == 1) {
                    parentNode.setIsLeaf(0);
                    tbSysDicGroupServiceImpl.update(parentNode);
                }
            }
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
    * Delete.
    *
    * @param ids the ids
    * @return the ajax json
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxJson delete(@RequestParam String ids) throws Exception {
        try {
            String[] dicGroupIds = ids.split(",");
            TbSysLoginmsg sessionUser = getSessionUser();
            for (String dicGroupId : dicGroupIds) {
                // 根据id查找子节点
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("dicGroupId", dicGroupId);
                param.put("isDelete", Constants.DELETE_N);
                TbSysDicGroup node = tbSysDicGroupServiceImpl.queryByParaMap(param);
                // 删除子节点
                TbSysDicGroup tbSysDicGroup = new TbSysDicGroup();
                tbSysDicGroup.setDicGroupId(dicGroupId);
                tbSysDicGroup.setIsDelete(Constants.DELETE_Y);
                tbSysDicGroup.setModifier(sessionUser.getLoginCode());
                tbSysDicGroup.setModifieDate(new Date());
                tbSysDicGroupServiceImpl.update(tbSysDicGroup);
                // 根据子节点的parentCode查询子节点数目
                Map<String, Object> rowParam = new HashMap<String, Object>();
                rowParam.put("parentCode", node.getParentCode());
                rowParam.put("isDelete", Constants.DELETE_N);
                List<ItemNode> rows = tbSysDicGroupServiceImpl.queryTreeData(rowParam);
                if (rows.size() == 0) {
                    // 更新父节点
                    Map<String, Object> parentParam = new HashMap<String, Object>();
                    parentParam.put("dicGroupCode", node.getParentCode());
                    parentParam.put("isDelete", Constants.DELETE_N);
                    TbSysDicGroup parentNode = tbSysDicGroupServiceImpl.queryByParaMap(parentParam);
                    parentNode.setIsLeaf(new Integer(1));
                    tbSysDicGroupServiceImpl.update(parentNode);
                }
            }
            return ajaxJson;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
    }

    /**
    * Exp excel.
    *
    * @return the ajax json
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/expExcel", method = RequestMethod.POST)
    public AjaxJson expExcel() throws Exception {
        try {
            Map<String, Object> param = this.getRequestMapSingle();
            String[] titles = (String[]) param.get("titles[]");
            String[] fields = (String[]) param.get("fields[]");
            Page page = new Page((String) param.get("sidx"), (String) param.get("sord"));
            param.put("isDelete", Constants.DELETE_N);
            ExportExcel ee = new ExportExcel();
            List rows = tbSysDicGroupServiceImpl.queryListByOrder(page, param);
            String path = ee.exportExcel(request, response, 40000, titles, fields, rows, TbSysDicGroup.class.getName());
            ajaxJson.setResult(path);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return ajaxJson;
    }

    /**
    * Check input field.
    *
    * @param inputName the input name
    * @param inputValue the input value
    * @return the json object
    * @throws Exception the exception
    * @author wangwenbo
    * @date 2018/01/17
    */
    @ResponseBody
    @RequestMapping(value = "/checkInputField", method = RequestMethod.POST)
    public JSONObject checkInputField(String inputName, String inputValue) throws Exception {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put(inputName, inputValue);
            param.put("isDelete", Constants.DELETE_N);
            List rows = tbSysDicGroupServiceImpl.queryListByParaMap(param);
            if (rows != null && rows.size() > 0) {
                json.put("valid", false);
            } else {
                json.put("valid", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(e);
        }
        return json;
    }
}
